package com.sm.honkon.ui.model

import android.os.CountDownTimer
import au.com.safie.user.app.util.CacheUtil
import com.blankj.utilcode.util.ToastUtils
import com.sm.honkon.app.network.apiService
import com.sm.honkon.app.utils.SendCodeHelper
import com.sm.honkon.data.bean.UserInfo
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.callback.databind.BooleanObservableField
import me.hgj.jetpackmvvm.callback.databind.StringObservableField
import me.hgj.jetpackmvvm.ext.request
import kotlin.random.Random

class ResetAdminViewModel : BaseViewModel() {

    val admin: UserInfo? = CacheUtil.getUser()
    val mobile = StringObservableField()
    val password = StringObservableField()
    val myCode = StringObservableField()
    val countDownTip = StringObservableField("获取验证码")
    val isCountDown = BooleanObservableField(false)
    val code = Random.nextInt(9999)
    val countDownTimer = object : CountDownTimer(60 * 1000, 1000) {
        override fun onTick(millisUntilFinished: Long) {
            isCountDown.set(true)
            countDownTip.set("重新发送(${millisUntilFinished / 1000L})")
        }

        override fun onFinish() {
            isCountDown.set(false)
            countDownTip.set("获取验证码")
        }

    }

    fun login(back:()->Unit) {
        val mobile = mobile.get()
        val password = password.get()
        if (mobile.isEmpty()) {
            ToastUtils.showShort("请输入手机号/工号")
            return
        }
        if (password.isEmpty()) {
            ToastUtils.showShort("请输入密码")
            return
        }
        if (myCode.get().isEmpty()) {
            ToastUtils.showShort("请输入验证码")
            return
        }
        if (myCode.get() != code.toString()) {
            ToastUtils.showShort("请输入正确的验证码")
            return
        }
        admin?.let {
            it.password = password
            CacheUtil.setUser(it)
            back.invoke()
        }
    }

    fun getSmsCode() {
        admin?.let {
            if (mobile.get().isEmpty()) {
                ToastUtils.showShort("请输入手机号/工号")
                return@let
            }
            if (it.mobile != mobile.get()) {
                ToastUtils.showShort("账号不存在")
                return@let
            }
            request(
                { apiService.getCode(SendCodeHelper.createUrl(it.mobile, code.toString())) },
                {})
            countDownTimer.start()
        }
    }
}